import React, { useState, useLayoutEffect, useEffect } from "react";
import { List, message } from "antd";
import { getArticleList } from "@/apis/articlesApi";
import { Article } from "@/apis/shared.ts";
import ArticleItem from "@/components/ArticleItem.tsx";
import MyVirtualList from "@/components/VirtualList";
import store from "@/store";
import {
  saveArticleListCurrentPage,
  saveArticleListData,
  saveArticleListScollTop,
} from "@/store/ArticleTempData";

const App: React.FC = () => {
  // 文章列表数据
  const [data, setData] = useState<Article[]>([]);
  // 当前页数
  const [currentPage, setCurrentPage] = useState(1);
  // 是否有更多数据
  const [hasMore, setHasMore] = useState<boolean>(true);

  // 封装一个函数，用于传递给子组件，做一下兼容处理
  const updateData = (updater: (prevData: Article[]) => Article[]) => {
    setData(updater);
  };

  useLayoutEffect(() => {
    console.log("dddddd")
    if (!store.getState().ArticleTempDataStore.articleListData) return;
    console.log("ssssss")
    setData(store.getState().ArticleTempDataStore.articleListData); // 设置文章列表
    setCurrentPage(
      store.getState().ArticleTempDataStore.articleListCurrentPage
    ); // 设置当前页数
    window.scrollTo(
      0,
      store.getState().ArticleTempDataStore.articleListScollTop
    ); // 滚动到指定位置
  }, []);

  useEffect(() => {
    return () => {
      console.log("组件即将卸载");
      // 组件卸载时，保存文章列表数据
      store.dispatch(saveArticleListData(data));
      // 保存文章列表当前页数
      store.dispatch(saveArticleListCurrentPage(currentPage));
      // 保存文章列表滚动位置
      store.dispatch(saveArticleListScollTop(window.scrollY));
    };
  }, [data, currentPage]);

  const getData = async () => {
    console.log("getData has been called");
    const res = await getArticleList({
      page: currentPage,
      pageSize: 10,
    });

    // 判断是否有更多数据
    if (res.data?.length === 0) {
      // 没有更多数据
      setHasMore(false);
      message.info("没有更多文章了");
    } else {
      // 有更多数据
      setData((prevData) => [...prevData, ...(res.data || [])]);
      setCurrentPage((prevPage) => prevPage + 1); // 更新当前页数以便下次加载下一页
    }
  };

  return (
    <div
      style={{
        display: "flex",
        justifyContent: "center",
        alignItems: "center",
      }}
    >
      <MyVirtualList
        listStyle={{
          maxWidth: "1000px",
          padding: "0 20px",
          width: "100%",
          textAlign: "center",
        }}
        getData={getData}
        hasMoreData={hasMore}
      >
        <List style={{ textAlign: "left", margin: "0 auto" }}>
          {data.map((item: Article) => (
            <div key={item._id} style={{ textAlign: "left" }}>
              <ArticleItem item={item} setData={updateData} />
            </div>
          ))}
        </List>
      </MyVirtualList>
    </div>
  );
};

export default App;
